package ch13;

/**
 * Created by zhangyunqi on 2017/9/23.
 */

public class Searching {
    public static Comparable linearSearch(Comparable[] data, Comparable target) {
        Comparable result = null;
        int index = 0;
        while (result == null && index < data.length) {
            if (data[index].compareTo ( target ) == 0)
                result = data[index];
            index++;
        }
        return result;
    }

    public static Comparable binarySearch(Comparable[] data, Comparable target) {
        Comparable result = null;
        int first = 0, last = data.length - 1, mid;

        while (result == null && first <= last) {

            mid = (first + last) / 2;

            if (data[mid].compareTo ( target ) == 0)
                result = data[mid];
            else if (data[mid].compareTo ( target ) > 0)
                last = mid - 1;
            else
                first = mid + 1;

        }
        return result;

    }
}
